import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/main',
      children: [
        {
          path: '/main',
          name: 'Main',
          redirect: '/home',
          component: () => import('@/pages/main/index.vue'),
          children: [
            {
              path: '/home',
              name: 'Home',
              component: () => import('@/pages/home/index.vue')
            },
            {
              path: '/share',
              name: 'share',
              component: () => import('@/pages/share/index.vue')
            },
            {
              path: '/product',
              name: 'product',
              component: () => import('@/pages/product/index.vue')
            },
            {
              path: '/upkeep',
              name: 'upkeep',
              component: () => import('@/pages/upkeep/index.vue')
            }
          ]
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/pages/login/index.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  // 如果有token去登录页面则不通过
  if (to.path === '/login' && localStorage.getItem('token')) {
    next('/home')
  } else if (to.path !== '/login' && !localStorage.getItem('token')) {
    next('/login')
  } else {
    next()
  }
})

export default router
